package org.lovebugs.utils;
public class BitConvertor {
	/**
	 * 2byte
	 * 
	 * @param i
	 * @return
	 */
	public static byte[] shortToByteArray(short i) {
		byte[] result = new byte[2];
		result[1] = (byte) ((i >>> 8) & 0xFF);
		result[0] = (byte) (i & 0xFF);
		return result;
	}
	
	public static byte[] sToBA(short i) {
		byte[] result = new byte[2];
		result[0] = (byte) ((i >>> 8) & 0xFF);
		result[1] = (byte) (i & 0xFF);
		return result;
	}

	public static byte[] intToByteArray(int i) {
		byte[] result = new byte[4];
		result[3] = (byte) ((i >>> 24) & 0xFF);
		result[2] = (byte) ((i >>> 16) & 0xFF);
		result[1] = (byte) ((i >>> 8) & 0xFF);
		result[0] = (byte) (i & 0xFF);
		return result;
	}
	
	public static byte[] iToBA(int i) {
		byte[] result = new byte[4];
		result[0] = (byte) ((i >>> 24) & 0xFF);
		result[1] = (byte) ((i >>> 16) & 0xFF);
		result[2] = (byte) ((i >>> 8) & 0xFF);
		result[3] = (byte) (i & 0xFF);
		return result;
	}

	public static byte[] concatAll(byte[] first, byte[]... rest) {
		int totalLength = first.length;
		for (byte[] array : rest) {
			totalLength += array.length;
		}
		int offset = first.length;
		byte[] result = new byte[totalLength];
		System.arraycopy(first, 0, result, 0, offset);
		for (byte[] array : rest) {
			System.arraycopy(array, 0, result, offset, array.length);
			offset += array.length;
		}
		return result;
	}

	public static int bytesToInt(byte[] intByte) {
		int fromByte = 0;
		for (int i = 0; i < 4; i++) {
			int n = (intByte[i] < 0 ? (int) intByte[i] + 256 : (int) intByte[i]) << (8 * i);
			fromByte += n;
		}
		return fromByte;
	}

	public static short bytesToShort(byte[] intByte) {
		short fromByte = 0;
		for (int i = 0; i < 2; i++) {
			int n = (intByte[i] < 0 ? (int) intByte[i] + 256 : (int) intByte[i]) << (8 * i);
			fromByte += n;
		}
		return fromByte;
	}
	
	public static short bToS(byte[] intByte) {
		short fromByte = 0;
		for (int i = 0; i < 2; i++) {
			int n = (intByte[i] < 0 ? (int) intByte[i] + 256 : (int) intByte[i]) << (8 * (2-i-1));
			fromByte += n;
		}
		return fromByte;
	}

	public static byte[] longToByteArray(long i) {
		byte[] result = new byte[4];
		result[3] = (byte) ((i >>> 24) & 0xFF);
		result[2] = (byte) ((i >>> 16) & 0xFF);
		result[1] = (byte) ((i >>> 8) & 0xFF);
		result[0] = (byte) (i & 0xFF);
		return result;
	}
}